package com.qf.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.config.IdWorker;
import com.qf.model.StandardReport;
import com.qf.model.StandardSubmit;
import com.qf.service.EsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 和ES交互的service
 * @author lenovo
 * @version V1.0
 * @Date 2021/11/25 12:18
 */
@Service
@Slf4j
public class EsServiceImpl implements EsService {
    private final String INDEX_NAME = "sms_submit_log2022";

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private IdWorker idWorker = new IdWorker();

    @Override
    public void add(StandardSubmit standardSubmit) throws Exception{
        //设置索引名
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index(INDEX_NAME);
        //设置文档id
        //如果为null说明是策略模块发送的消息，如果不为null，是网关模块发送的消息
        indexRequest.id(standardSubmit.getSequenceId());

        Map map= objectMapper.readValue(objectMapper.writeValueAsString(standardSubmit), Map.class);

        indexRequest.source(map);
        IndexResponse resp = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        if (!resp.getResult().toString().equalsIgnoreCase("created")){
            log.info("【搜索模块 - 添加文档】日志文档添加失败！！文档对象 standardSubmit={}",standardSubmit);
        }else {
            log.info("【搜索模块 - 添加文档】日志文档添加成功！！standardSubmit={}",standardSubmit);
        }

    }

    @Override
    public void updateLog(StandardReport report) throws IOException {
        //1.request
        UpdateRequest request = new UpdateRequest();
        request.index(INDEX_NAME);
        request.id(report.getSequenceId());

        //2.封装
        Map source = new HashMap();
        source.put( "reportState",report.getState());
        source.put("errorCode",report.getErrorCode());
        request.doc(source);

        //3.执行并获取结果
        UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);

        //4.根据结果判断执行是否成功
        String res = response.getResult().toString();
        if (!res.equalsIgnoreCase("updated")){
            log.info("【搜索模块 - 修改文档】日志文档修改失败！！文档对象 standardtReport={}",report);
        }else {
            log.info("【搜索模块 - 修改文档】日志文档修改成功,report={}",report);

        }
    }

    /**
     * 根据条件查询日志集合数据返回
     * @param paras
     */
    @Override
    public List<Map> searchLog(String paras) throws Exception{

        SearchResponse response = findData(paras);
        //封装数据
        List<Map> data = new ArrayList<>();
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            Map<String, Object> source = hit.getSourceAsMap();
            //显示高亮的数据
            HighlightField messageContent = hit.getHighlightFields().get("messageContent");
            if (messageContent != null){
                String msgContent = messageContent.fragments()[0].toString();
                source.put("messageContent",msgContent);
            }
            data.add(source);
        }
        return data;

    }

    /**
     * 根据条件查询日志总条数
     * @param paras
     */
    @Override
    public Long searchLogCount(String paras) throws IOException {
        SearchResponse response = findData(paras);
        //返回数据条数
        long count = response.getHits().getTotalHits().value;
        return count;

    }

    /**
     * 统计报表查询
     * @param paras
     */
    @Override
    public Map<String, Long> statSendStatus(String paras) throws Exception {
        //1. 获取索引名称创建request    TODO 根据parameter中的startTime和endTime判断查询的哪些索引
        SearchRequest request = new SearchRequest();
        request.indices(INDEX_NAME);

        //2.将json序列化map
        Map parameter = objectMapper.readValue(paras, Map.class);

        //3. 封装
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //3.1 设置聚合函数
        sourceBuilder.aggregation(AggregationBuilders.histogram("agg").field("reportState").interval(1));

        //3.2 设置查询条件
        // clientID客户id,keyword关键字,mobile手机号,startTime开始时间,endTime结束时间
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // clientID客户id
        Integer clientID = (Integer) parameter.get("clientID");
        if(clientID != null){
            boolQuery.must(QueryBuilders.termQuery("clientID",clientID));
        }
        // startTime开始时间,endTime结束时间
        Long startTime = (Long) parameter.get("startTime");
        Long endTime = (Long) parameter.get("endTime");
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("sendTime");
        if(startTime != null){
            rangeQuery.gte(startTime);
        }
        if(endTime != null){
            rangeQuery.lte(endTime);
        }
        boolQuery.must(rangeQuery);
        sourceBuilder.query(boolQuery);
        // 将sourceBuilder设置给request
        request.source(sourceBuilder);

        //4. 执行并获取返回结果
        SearchResponse resp = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        Aggregations aggregations = resp.getAggregations();
        Histogram agg = aggregations.get("agg");
        List<? extends Histogram.Bucket> buckets = agg.getBuckets();
        //5. 封装数据
        Map<String, Long> data = new HashMap<>();
        for (Histogram.Bucket bucket : buckets) {
            Double key = (Double) bucket.getKey();
            if(key == 0.0){
                // 短信发送成功
                data.put("0",bucket.getDocCount());
            }else if(key == 1.0){
                //短信发送失败
                data.put("1",bucket.getDocCount());
            }else{
                //短信未返回状态
                data.put("2",bucket.getDocCount());
            }
        }
        //6. 返回
        return data;
    }

    /**
     * 根据传入的JSON字符串去查询es中查询数据
     * @param paras
     * @return
     * @throws IOException
     */
    public SearchResponse findData(String paras) throws IOException {
        //1.创建searchRequest
        SearchRequest request = new SearchRequest(INDEX_NAME);
        //将json字符串序列化为map
        Map paraMap = objectMapper.readValue(paras, Map.class);

        //2.封装查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //3.设置复合查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //clientID
        Integer clientID = (Integer) paraMap.get("clientID");
        if (clientID != null){
            boolQuery.must(QueryBuilders.termQuery("clientID",clientID));
        }
        // keyword关键字
        String keyword = (String) paraMap.get("keyword");
        if(!StringUtils.isEmpty(keyword)){
            boolQuery.must(QueryBuilders.matchQuery("messageContent",keyword));
        }
        // mobile手机号
        String mobile = (String) paraMap.get("mobile");
        if(!StringUtils.isEmpty(mobile)){
            boolQuery.must(QueryBuilders.termQuery("destMobile",mobile));
        }
        // startTime开始时间,endTime结束时间
        Long startTime = (Long) paraMap.get("startTime");
        Long endTime = (Long) paraMap.get("endTime");
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("sendTime");
        if(startTime != null){
            rangeQuery.gte(startTime);
        }
        if(endTime != null){
            rangeQuery.lte(endTime);
        }
        boolQuery.must(rangeQuery);
        // 设置给sourceBuilder
        sourceBuilder.query(boolQuery);

        //3.2 设置分页信息
        Integer start = (Integer) paraMap.get("start");
        Integer rows = (Integer) paraMap.get("rows");
        sourceBuilder.from(start);    // TODO 是当前页, 还是起始索引
        sourceBuilder.size(rows);

        //3.3 设置高亮信息
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("messageContent");
        highlightBuilder.fragmentSize(50);
        highlightBuilder.preTags((String) paraMap.get("highLightPreTag"));
        highlightBuilder.postTags((String) paraMap.get("highLightPostTag"));
        sourceBuilder.highlighter(highlightBuilder);

        request.source(sourceBuilder);

        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        return response;

    }
}
